package com.xltt.watchfota;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.RecoverySystem;
import android.os.RemoteException;
import android.provider.Settings;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.basewin.mdm.aidl.AidlSystem;
import com.basewin.mdm.aidl.IResultCallback;
import com.google.gson.Gson;
import com.lzy.okgo.db.DownloadManager;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.Progress;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.xltt.fota.UpdateAppBean;
import com.xltt.fota.UpdateAppManager;
import com.xltt.fota.UpdateCallback;
import com.xltt.fota.service.DownloadService;
import com.xltt.fota.utils.OkGoUpdateHttpUtil;
import com.xltt.watchfota.bean.ApkBean;
import com.xltt.watchfota.bean.Data;
import com.xltt.watchfota.bean.FotaInfo;
import com.xltt.watchfota.bean.VersionInfo;
import com.xltt.watchfota.utils.CProgressDialogUtils;
import com.xltt.watchfota.utils.FileUtils;
import com.xltt.watchfota.utils.NetWorkUtils;
import com.xltt.watchfota.utils.ToastUtil;
import com.xltt.watchfota.view.CircularProgressView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends BaseActivity {

    private Button mUpgradeBtn;
    private TextView mDownloadProgressText;
    private CircularProgressView mDownloadProgress;
    private UpdateAppManager mUpdateAppManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("zhanghui","onCreate()");
        setContentView(R.layout.activity_main);
        initViews();
        initBatteryInfo(this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.d("zhanghui","onResume()");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("zhanghui","onPause()");
    }

    private void initViews(){
        TextView versionName = findViewById(R.id.version_name);
        versionName.setText(getString(R.string.current_version_name) + "\n" + Build.DISPLAY);
        mDownloadProgress = findViewById(R.id.progress);
        mDownloadProgressText = findViewById(R.id.download_progress);
        mUpgradeBtn = findViewById(R.id.check_btn);
        mUpgradeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //1.判断电量
                if(getBatteryLevel() < 30){
                    ToastUtil.show(MainActivity.this,getString(R.string.battry_low_tip));
                    return;
                }
                //2.判断网络
                if(!NetWorkUtils.isAvailable(MainActivity.this)){
                    ToastUtil.show(MainActivity.this,getString(R.string.please_connect_netwrok));
                    return;
                }
                //3.检查升级
                upgrade();
            }
        });
    }

    /**
     * 升级
     */
    private void upgrade(){
        mUpgradeBtn.setEnabled(false);
        String eid = Settings.Global.getString(getContentResolver(),"watch_eid");
        String versionCode = getSystemVersion();
        Log.d(TAG,"eid = " + eid + ",versionCode = " + versionCode);
        //请求参数
        Map<String, String> params = new HashMap<>();

//        params.put("eid",TextUtils.isEmpty(eid) ? "eid0000002ID" : eid);
//        params.put("currentVersionCode", "611");

        params.put("eid",TextUtils.isEmpty(eid) ? "eid0000001ID" : eid);
        params.put("currentVersionCode", versionCode);
        //请求头
        HttpHeaders header = new HttpHeaders();
        header.put("Content-Type","application/json");
        header.put("X-ENV-TYPE","testing");//development,testing,reproduction,production
        header.put("X-SERVICEID","s3");
        header.put("X-CLIENTTYPE","3");
        header.put("X-LANGUAGE","en");//zh,my,th,en
        new UpdateAppManager
                .Builder()
                //请求头信息
                .setHttpHeaders(header)
                //必须设置，当前Activity
                .setActivity(this)
                //必须设置，实现httpManager接口的对象
                .setHttpManager(new OkGoUpdateHttpUtil())
                //必须设置，更新地址
                .setUpdateUrl(getHost())
                //以下设置，都是可选
                //设置请求方式，默认get
                .setPost(true)
                //添加自定义参数，默认version=1.0.0（app的versionName）；apkKey=唯一表示（在AndroidManifest.xml配置）
                .setParams(params)
                //设置apk下砸路径，默认是在下载到sd卡下/Download/1.0.0/test.apk
                .setTargetPath(FileUtils.getDownloadFilePath())
                //设置appKey，默认从AndroidManifest.xml获取，如果，使用自定义参数，则此项无效
//                .setAppKey("ab55ce55Ac4bcP408cPb8c1Aaeac179c5f6f")

                .build()
                //检测是否有新版本
                .checkNewApp(new UpdateCallback() {
                    /**
                     * 网络请求之前
                     */
                    @Override
                    public void onBefore() {
                        CProgressDialogUtils.showProgressDialog(MainActivity.this);
                    }

                    /**
                     * 解析json,自定义协议
                     *
                     * @param json 服务器返回的json
                     * @return UpdateAppBean
                     */
                    @Override
                    protected UpdateAppBean parseJson(String json) {
                        Log.d("zhanghui","server response = " + json);
                        UpdateAppBean mUpdateAppBean = new UpdateAppBean();
                        FotaInfo mFotaInfo = new Gson().fromJson(json, FotaInfo.class);
                        int code = mFotaInfo.getCode();
                        if(code != 200){
                            mUpdateAppBean.setUpdate("No");
                            return mUpdateAppBean;
                        }
                        String versionCode = mFotaInfo.getData().getVersion();
                        VersionInfo mVersionInfo = mFotaInfo.getData().getVersionInfo().get(0);
                        Data mData = mFotaInfo.getData();
                        String downloadUri = mVersionInfo.getUri();
                        String changeLog = mVersionInfo.getWhatsNew();
                        String size = mVersionInfo.getPackageSize();

                        mUpdateAppBean.setUpdate("Yes");//（必须）是否更新Yes,No
                        mUpdateAppBean.setNewVersion(versionCode);//（必须）新版本号
                        mUpdateAppBean.setApkFileUrl(downloadUri);//（必须）下载地址
                        mUpdateAppBean.setUpdateLog(changeLog);//（必须）更新内容
                        //大小，不设置不显示大小，可以不设置
                        mUpdateAppBean.setTargetSize(size);
                        mUpdateAppBean.setUpdateDefDialogTitle(String.format(getString(R.string.check_version_title)));
                        //是否强制更新，可以不设置
                        mUpdateAppBean.setConstraint(mData.getMandatoryUpgrade());
                        mUpdateAppBean.setIsZipFile(true);
                        return mUpdateAppBean;
                    }

                    /**
                     * 有新版本
                     *
                     * @param updateApp        新版本信息
                     * @param updateAppManager app更新管理器
                     */
                    @Override
                    public void hasNewApp(final UpdateAppBean updateApp, final UpdateAppManager updateAppManager) {
                        showDownloadDialog(updateApp,updateAppManager);
                    }


                    /**
                     * 网路请求之后
                     */
                    @Override
                    public void onAfter() {
                        CProgressDialogUtils.cancelProgressDialog(MainActivity.this);
                    }

                    /**
                     * 没有新版本
                     */
                    @Override
                    public void noNewApp(String error) {
                        ToastUtil.show(MainActivity.this,getString(R.string.current_last_version));
                        updateButton(LAST_VERSION);
                    }
                });

    }


    /**
     * 下载升级包dialog
     * @param updateApp
     * @param updateAppManager
     */
    private void showDownloadDialog(final UpdateAppBean updateApp, final UpdateAppManager updateAppManager) {
        String targetSize = updateApp.getTargetSize();
        String updateLog = updateApp.getUpdateLog();
        String msg = "";
        if (!TextUtils.isEmpty(targetSize)) {
            msg = String.format(getString(R.string.new_version_size), FileUtils.bytes2kb(Double.valueOf(targetSize))) + "\n\n";
        }
        if (!TextUtils.isEmpty(updateLog)) {
            msg += updateLog;
        }
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.show();  //注意：必须在window.setContentView之前show
        Window window = dialog.getWindow();
        window.setContentView(R.layout.download_dialog_layout);
        TextView downloadTitle = window.findViewById(R.id.version_title);
        downloadTitle.setText(updateApp.getUpdateDefDialogTitle());
        TextView downloadContent = window.findViewById(R.id.version_content);
        downloadContent.setText(msg);
        Button cancelButton = window.findViewById(R.id.cancel_download_btn);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateButton(DOWNLOAD_FAILD);
                dialog.dismiss();
            }
        });
        Button downloadButton = window.findViewById(R.id.download_btn);
        downloadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isMemoryEnough(Double.valueOf(targetSize))){
                    updateButton(DOWNLOAD_FAILD);
                    ToastUtil.show(MainActivity.this,getString(R.string.storage_space_error));
                    return;
                }
                mUpdateAppManager = updateAppManager;
                updateAppManager.download(new DownloadService.DownloadCallback() {
                    private DecimalFormat mDecimalFormat;
                    @Override
                    public void onStart() {
                        Log.d("zhanghui","开始下载");
                        acquireWakeLock();
                        updateButton(DOWNLOADING);
                        CProgressDialogUtils.showProgressDialog(MainActivity.this,getString(R.string.check_ota_file));
                        this.mDecimalFormat = new DecimalFormat("0.0");
                        //HProgressDialogUtils.showHorizontalProgressDialog(SoftwareUpdateActivity.this, getString(R.string.download_progress), false);
                    }

                    @Override
                    public void onProgress(float progress, long totalSize) {
                        CProgressDialogUtils.cancelProgressDialog(MainActivity.this);
                        Log.d("zhanghui","下载大小 = " + totalSize + ",进度 = " + progress);
                        int mprogress = Math.round(progress * 100);
                        mDownloadProgress.setProgress(mprogress);
                        mDownloadProgressText.setText(mDecimalFormat.format(progress * 100) + "%");
                        //HProgressDialogUtils.setProgress(Math.round(progress * 100));
                    }

                    @Override
                    public void setMax(long total) {

                    }


                    @Override
                    public boolean onFinish(File file) {
                        //HProgressDialogUtils.cancel();
                        releaseWakeLock();
                        updateButton(DOWNLOAD_SUCCESS);
                        mDownloadProgressText.setText(getString(R.string.download_success));
                        fileCommand(file);
                        dialog.dismiss();
                        showUpgradeDialog(updateApp,updateAppManager,file);
                        return true;
                    }

                    @Override
                    public void onError(String msg) {
                        Log.d("zhanghui","开始失败");
                        releaseWakeLock();
                        updateButton(DOWNLOAD_FAILD);
                        mDownloadProgressText.setText(getString(R.string.download_faild));
                        ToastUtil.show(MainActivity.this,msg);
                        //HProgressDialogUtils.cancel();

                    }

                    @Override
                    public boolean onInstallAppAndAppOnForeground(File file) {
                        return false;
                    }
                });
                dialog.dismiss();
            }
        });
    }

    public static final int DOWNLOADING = 1;
    public static final int DOWNLOAD_SUCCESS = 2;
    public static final int DOWNLOAD_FAILD = 3;
    public static final int LAST_VERSION = 4;
    private void updateButton(int index){
        switch (index){
            case DOWNLOADING:
                mUpgradeBtn.setEnabled(false);
                mUpgradeBtn.setText(getString(R.string.downloading));
                break;
            case DOWNLOAD_SUCCESS:
            case DOWNLOAD_FAILD:
                mUpgradeBtn.setEnabled(true);
                mUpgradeBtn.setText(getString(R.string.check_version));
                break;
            case LAST_VERSION:
                mUpgradeBtn.setEnabled(false);
                mUpgradeBtn.setText(getString(R.string.last_version));
                break;
        }
    }


    /**
     * 是否升级dialog
     * @param updateApp
     * @param updateAppManager
     */
    private void showUpgradeDialog(final UpdateAppBean updateApp, final UpdateAppManager updateAppManager,File file){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.show();  //注意：必须在window.setContentView之前show
        Window window = dialog.getWindow();
        window.setContentView(R.layout.upgrade_dialog_layout);
        Button cancelButton = window.findViewById(R.id.cancel_upgrade_btn);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        Button downloadButton = window.findViewById(R.id.upgrade_btn);
        downloadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                Log.d(TAG,"开始fota升级，文件路径 = " + file.getPath() + ",文件名 = " + file.getName());
                try {
                    RecoverySystem recoverySystem = (RecoverySystem) MainActivity.this.getSystemService("recovery");
                    recoverySystem.installPackage(MainActivity.this, file);
                } catch (Exception e) {
                    e.printStackTrace();
                }
//                AidlSystem mAidlSystem = ((BaseApplication)getApplication()).getAidl();
//                if(mAidlSystem == null){
//                    Log.d(TAG,"aidl升级服务获取失败，无法调用升级功能，文件路径 = " + file.getPath() + ",文件名 = " + file.getName());
//                    return;
//                }
//                try {
//                    mAidlSystem.updateFirmware3("ap",file.getPath(),file.getName(),true,mIResultCallback);
//                } catch (RemoteException e) {
//                    e.printStackTrace();
//                }
            }
        });
    }

    private IResultCallback.Stub mIResultCallback = new IResultCallback.Stub(){
        @Override
        public void result(int comand, String strJson) throws RemoteException {
            Log.d("zhanghui","正在升级，comand = " + comand + ",strJson = " + strJson);

        }
    };


    @Override
    protected void onDestroy() {
        Log.d("zhanghui","onDestroy()");
        if(mUpdateAppManager != null){
            mUpdateAppManager.stop();
        }
        //1.停止所有下载任务
        if(DownloadManager.getInstance().getAll().size() > 0){
            Log.d("zhanghui","取消所有下载升级包任务");
            OkDownload.getInstance().pauseAll();
        }
        //2.释放休眠锁
        releaseWakeLock();
        //3.取消监听电量广播
        destroyBatteryInfo(this);
        //((BaseApplication)getApplication()).unbindService();
        super.onDestroy();
    }
}